package com.hd123.rumba.gwt.widget2.client.fielddef;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

/**
 * 枚举类型字段的定义
 * 
 * @author LiQi
 * 
 */
public class EnumFieldDef extends FieldDef {

  /** 可选值 */
  protected String[][] values;
  protected HashMap valuesMap;

  public EnumFieldDef(String name, String caption, boolean nullable, String[][] values) {
    super(name, caption, nullable);
    valuesMap = new HashMap();
    setValues(values);
  }

  public FieldDef clone() {
    return new EnumFieldDef(name, caption, nullable, values);
  }

  public boolean validateText(String text, StringBuffer message) {
    return validateText(text, message, true);
  }

  public boolean validateText(String text, StringBuffer message, boolean checkNullable) {
    String value = null;
    // 传入文本不为null则检查文本是否存在于values中，传入文本为null则直接传递给validate
    if (text != null) {
      for (int i = 0; i < values.length; i++)
        if (values[i][1].equals(text))
          value = values[i][0];
      if (value == null) {
        finalizeMessage(message, "\"" + text + "\"不在可选值范围内");
        return false;
      }
    }
    return validate(value, message, checkNullable);
  }

  public boolean validate(String value, StringBuffer message) {
    return validate(value, message, true);
  }

  /**
   * 验证传入的值是否合法
   * 
   * @param value
   * @return
   */
  public boolean validate(String value, StringBuffer message, boolean checkNullable) {
    value = "".equals(value) ? null : value;
    boolean result = super.validate(value, message, checkNullable);
    if (value == null)
      return result;

    if (getEnumNames().contains(value))
      return true;

    finalizeMessage(message, "\"" + value + "\"不在可选值范围内");
    return false;
  }

  public String[][] getValues() {
    return values;
  }

  public void setValues(String[][] values) {
    this.values = values;
    for (int i = 0; i < values.length; i++) {
      valuesMap.put(values[i][0], values[i][1]);
    }
  }

  public Set getEnumNames() {
    return valuesMap.keySet();
  }

  public Collection getEnumCaptions() {
    return valuesMap.values();
  }

  public String getEnumCaption(String enumName) {
    return (String) valuesMap.get(enumName);
  }

}
